<template>
  <div class="statistic-container">
    <!-- 筛选区域 -->
    <div class="filter-bar">
      <el-select
        v-model="selectedClassId"
        placeholder="请选择班级"
        @change="handleClassChange"
        style="width: 200px; margin-right: 16px"
      >
        <el-option
          v-for="cls in sortedTeacherClasses"
          :key="cls.id"
          :label="`${cls.grade}年级${cls.name}`"
          :value="cls.id"
        />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        @change="handleDateChange"
        style="width: 320px; margin-right: 24px"
      />

      <el-button-group>
        <el-button
          :type="activeTimeRange === 'week' ? 'primary' : 'default'"
          @click="handleTimeRange('week')"
        >
          本周
        </el-button>
        <el-button
          :type="activeTimeRange === 'month' ? 'primary' : 'default'"
          @click="handleTimeRange('month')"
        >
          本月
        </el-button>
        <el-button
          :type="activeTimeRange === 'quarter' ? 'primary' : 'default'"
          @click="handleTimeRange('quarter')"
        >
          本季度
        </el-button>
        <el-button
          :type="activeTimeRange === 'year' ? 'primary' : 'default'"
          @click="handleTimeRange('year')"
        >
          本年
        </el-button>
      </el-button-group>
    </div>

    <!-- 班级统计卡片 -->
    <div class="class-card">
      <div class="class-info">
        <h2>{{ `${classInfo.grade}年级${classInfo.class_name}` }}</h2>
        <div class="stats">
          <div class="stat-item">
            <span class="label">总积分</span>
            <span class="value">{{ reportClassInfo.total || '0' }}</span>
          </div>
          <div class="stat-item">
            <span class="label">总加分</span>
            <span class="value add">{{ classInfo.total_add || '0' }}</span>
          </div>
          <div class="stat-item">
            <span class="label">总扣分</span>
            <span class="value minus">{{ classInfo.total_minus || '0' }}</span>
          </div>
        </div>
      </div>

      <div class="charts-row">
        <div class="chart-container">
          <h3>加分理由占比</h3>
          <div ref="addReasonChartRef" class="chart" />
        </div>
        <div class="chart-container">
          <h3>扣分理由占比</h3>
          <div ref="minusReasonChartRef" class="chart" />
        </div>
      </div>
    </div>

    <!-- 排名列表区域 -->
    <div class="rankings-container">
      <div class="ranking-list">
        <h3>学生积分排名</h3>
        <el-table :data="studentRanking" border>
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column prop="student_name" label="学生姓名" />
          <el-table-column prop="total" label="总积分" />
          <el-table-column prop="total_add" label="总加分" />
          <el-table-column prop="total_minus" label="总扣分" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="text"
                @click="handleViewDetail('student', scope.row.student_id, scope.row.student_name, scope.row.total)"
              >
                查看统计
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="ranking-list">
        <h3>小组积分排名</h3>
        <el-table :data="groupRanking" border>
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column prop="group_name" label="小组名称" />
          <el-table-column prop="total" label="总积分" />
          <el-table-column prop="total_add" label="总加分" />
          <el-table-column prop="total_minus" label="总扣分" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="text"
                @click="handleViewDetail('group', scope.row.group_id, scope.row.group_name, scope.row.total)"
              >
                查看统计
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailTitle"
      width="800px"
      destroy-on-close
    >
      <div class="detail-info">
        <h3>{{ detailName }}</h3>
        <div class="stats">
          <div class="stat-item">
            <span class="label">总积分</span>
            <span class="value">{{ detailTotal || '0' }}</span>
          </div>
          <div class="stat-item">
            <span class="label">总加分</span>
            <span class="value add">{{ detailStats.total_add || '0' }}</span>
          </div>
          <div class="stat-item">
            <span class="label">总扣分</span>
            <span class="value minus">{{ detailStats.total_minus || '0' }}</span>
          </div>
        </div>
      </div>

      <div class="charts-row">
        <div class="chart-container">
          <h3>加分理由占比</h3>
          <div ref="detailAddReasonChartRef" class="chart" />
        </div>
        <div class="chart-container">
          <h3>扣分理由占比</h3>
          <div ref="detailMinusReasonChartRef" class="chart" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { getStatistics, getReport, type StatisticsParams, type ReportParams } from '../../api/point';
import { listClasses, type ClassItem } from '../../api/classmgr'; // 假设已有班级列表接口

// 响应式数据
const allClasses = ref<ClassItem[]>([]);
const selectedClassId = ref<number>(0);
const dateRange = ref<string[]>([]);
const activeTimeRange = ref<'week' | 'month' | 'quarter' | 'year'>('week');

// 班级排序处理（新增）
const sortedTeacherClasses = computed(() => {
  // 先按年级升序，再按班级名称升序排序
  return [...allClasses.value].sort((a, b) => {
    if (a.grade !== b.grade) {
      return a.grade - b.grade;
    }
    // 假设班级名称是数字字符串，如"1班"、"2班"，提取数字进行比较
    const classA = parseInt(a.name);
    const classB = parseInt(b.name);
    return classA - classB;
  });
});

// 班级统计数据
const classInfo = ref<any>({});
const addReasons = ref<any[]>([]);
const minusReasons = ref<any[]>([]);
const reportClassInfo = ref<any>({});

// 排名数据
const studentRanking = ref<any[]>([]);
const groupRanking = ref<any[]>([]);

// 详情弹窗
const detailDialogVisible = ref(false);
const detailType = ref<'student' | 'group'>('student');
const detailId = ref<number>(0);
const detailName = ref('');
const detailTitle = ref('');
const detailStats = ref<any>({});
const detailAddReasons = ref<any[]>([]);
const detailMinusReasons = ref<any[]>([]);
const detailTotal = ref<any>({})

// 图表实例
let addReasonChart: echarts.ECharts | null = null;
let minusReasonChart: echarts.ECharts | null = null;
let detailAddReasonChart: echarts.ECharts | null = null;
let detailMinusReasonChart: echarts.ECharts | null = null;

// 初始化班级列表
const initClasses = async () => {
  try {
    const res = await listClasses();
    allClasses.value = res.content || [];
    const firstClass = sortedTeacherClasses.value[0];
    if (firstClass && firstClass.id) { // 额外判断元素和 id 的存在
        selectedClassId.value = firstClass.id;
    }
  } catch (error) {
    ElMessage.error('获取班级列表失败');
    console.error(error);
  }
};

// 计算时间范围
const calculateDateRange = (type: 'week' | 'month' | 'quarter' | 'year') => {
  const end = new Date();
  end.setHours(23, 59, 59, 999);
  
  const start = new Date();
  
  switch (type) {
    case 'week':
      // 自然周：周一到周日（本周一 00:00:00 到本周日 23:59:59）
      const day = start.getDay() || 7; // 转换为周一为1，周日为7
      start.setDate(start.getDate() - (day - 1)); // 回退到本周一
      start.setHours(0, 0, 0, 0);
      
      // 结束日期为本周日
      const sunday = new Date(start);
      sunday.setDate(start.getDate() + 6);
      end.setTime(sunday.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'month':
      // 自然月：本月1号 00:00:00 到本月最后一天 23:59:59
      start.setDate(1); // 本月1号
      start.setHours(0, 0, 0, 0);
      
      // 本月最后一天
      const lastDay = new Date(start.getFullYear(), start.getMonth() + 1, 0);
      end.setTime(lastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'quarter':
      // 自然季度：季度第一天到季度最后一天
      const month = start.getMonth();
      const quarterStartMonth = Math.floor(month / 3) * 3; // 0, 3, 6, 9
      
      // 季度第一天（如Q4为10月1日）
      start.setMonth(quarterStartMonth);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      
      // 季度最后一天（如Q4为12月31日）
      const quarterEndMonth = quarterStartMonth + 2;
      const quarterLastDay = new Date(start.getFullYear(), quarterEndMonth + 1, 0);
      end.setTime(quarterLastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'year':
      // 自然年：1月1日 00:00:00 到12月31日 23:59:59
      start.setMonth(0); // 1月
      start.setDate(1); // 1号
      start.setHours(0, 0, 0, 0);
      
      // 12月最后一天
      const yearLastDay = new Date(start.getFullYear(), 12, 0);
      end.setTime(yearLastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
  }
  
  // 格式化时间为 "YYYY-MM-DD HH:mm:ss"
  const format = (date: Date) => {
    return date.toISOString().slice(0, 19).replace('T', ' ');
  };
  
  // 调整为东八区
  start.setHours(start.getHours() + 8);
  end.setHours(end.getHours() + 8);
  
  return [format(start), format(end)];
};

// 加载班级统计数据
const loadClassStatistics = async () => {
  if (!selectedClassId.value || !dateRange.value.length) return;
  
  try {
    const params: StatisticsParams = {
      class_id: selectedClassId.value,
      start_time: dateRange.value[0],
      end_time: dateRange.value[1]
    };
    
    const res = await getStatistics(params);
    if (res.code === 200) {
      classInfo.value = res.content;
      addReasons.value = res.content.add_reasons;
      minusReasons.value = res.content.minus_reasons;
      updateClassCharts();
    }
  } catch (error) {
    ElMessage.error('获取班级统计数据失败');
    console.error(error);
  }
};

// 加载排名数据
const loadRankingData = async () => {
  if (!selectedClassId.value || !dateRange.value.length) return;
  
  try {
    const params: ReportParams = {
      class_id: selectedClassId.value,
      start_time: dateRange.value[0],
      end_time: dateRange.value[1]
    };
    
    const res = await getReport(params);
    if (res.code === 200) {
      reportClassInfo.value = res.content.class_info;
      studentRanking.value = res.content.student_ranking;
      groupRanking.value = res.content.group_ranking;
    }
  } catch (error) {
    ElMessage.error('获取排名数据失败');
    console.error(error);
  }
};

// 更新班级图表
const updateClassCharts = () => {
  if (addReasonChart) {
    addReasonChart.setOption(getPieChartOption(addReasons.value));
  }
  
  if (minusReasonChart) {
    minusReasonChart.setOption(getPieChartOption(minusReasons.value));
  }
};

// 更新详情图表
const updateDetailCharts = () => {
  // 先初始化图表实例
  initDetailCharts();

  if (detailAddReasonChart) {
    detailAddReasonChart.setOption(getPieChartOption(detailAddReasons.value));
  }
  
  if (detailMinusReasonChart) {
    detailMinusReasonChart.setOption(getPieChartOption(detailMinusReasons.value));
  }
};

// 饼图配置
const getPieChartOption = (data: any[]) => {
  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 10
    },
    series: [
      {
        name: '积分',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          name: item.reason,
          value: Math.abs(item.points),
          label: {
            show: true,
            formatter: `${item.reason}: ${item.points} (${item.percentage || item.personal_percentage}%)`
          }
        }))
      }
    ]
  };
};

// 事件处理
const handleClassChange = async() => {
  await loadClassStatistics();
  await loadRankingData();
};

const handleDateChange = async() => {
  if (dateRange.value.length) {
    await loadClassStatistics();
    await loadRankingData();
  }
};

const handleTimeRange = async(type: 'week' | 'month' | 'quarter' | 'year') => {
  activeTimeRange.value = type;
  dateRange.value = calculateDateRange(type);
};

const handleViewDetail = async (type: 'student' | 'group', id: number, name: string, total: string) => {
  if (!dateRange.value.length) return;
  
  detailType.value = type;
  detailId.value = id;
  detailName.value = name;
  detailTitle.value = `${type === 'student' ? '学生' : '小组'}统计详情`;
  detailDialogVisible.value = true;
  detailTotal.value = total;
  
  try {
    const params: StatisticsParams = {
      [type === 'student' ? 'student_id' : 'group_id']: id,
      start_time: dateRange.value[0],
      end_time: dateRange.value[1]
    };
    
    const res = await getStatistics(params);
    if (res.code === 200) {
      detailStats.value = res.content;
      detailAddReasons.value = res.content.add_reasons;
      detailMinusReasons.value = res.content.minus_reasons;
      
      // 等待弹窗渲染完成后更新图表
      await nextTick();
      updateDetailCharts();
    }
  } catch (error) {
    ElMessage.error(`获取${type === 'student' ? '学生' : '小组'}统计数据失败`);
    console.error(error);
  }
};

// 初始化图表
const initCharts = () => {
  // 班级图表
  if (addReasonChartRef.value) {
    addReasonChart = echarts.init(addReasonChartRef.value);
  }
  if (minusReasonChartRef.value) {
    minusReasonChart = echarts.init(minusReasonChartRef.value);
  }
  
  // 窗口大小变化时重绘
  window.addEventListener('resize', () => {
    addReasonChart?.resize();
    minusReasonChart?.resize();
    detailAddReasonChart?.resize();
    detailMinusReasonChart?.resize();
  });
};

// 初始化详情图表（在Dialog显示后调用）
const initDetailCharts = () => {
  if (detailAddReasonChartRef.value) {
    detailAddReasonChart = echarts.init(detailAddReasonChartRef.value);
  }
  if (detailMinusReasonChartRef.value) {
    detailMinusReasonChart = echarts.init(detailMinusReasonChartRef.value);
  }
};

// 引用
const addReasonChartRef = ref<HTMLElement>();
const minusReasonChartRef = ref<HTMLElement>();
const detailAddReasonChartRef = ref<HTMLElement>();
const detailMinusReasonChartRef = ref<HTMLElement>();

// 初始化
onMounted(async () => {
  await initClasses();
  dateRange.value = calculateDateRange('week');

  await loadClassStatistics();
  await loadRankingData();

  initCharts();
  // 数据加载完成后手动更新一次图表
  updateClassCharts();
  
  // 监听班级和日期变化
  watch([selectedClassId, dateRange], async() => {
    if (selectedClassId.value && dateRange.value.length) {
      await loadClassStatistics();
      await loadRankingData();
    }
  });
});
</script>

<style scoped>
.statistic-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.class-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.class-info {
  margin-bottom: 20px;
}

.stats {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.stat-item .label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-item .value {
  font-size: 20px;
  font-weight: bold;
}

.stat-item .add {
  color: #27ae60;
}

.stat-item .minus {
  color: #e74c3c;
}

.charts-row {
  display: flex;
  gap: 20px;
}

.chart-container {
  flex: 1;
  height: 400px;
}

.chart {
  width: 100%;
  height: calc(100% - 30px);
}

.rankings-container {
  display: flex;
  gap: 20px;
}

.ranking-list {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ranking-list h3 {
  margin-bottom: 16px;
}

.detail-info {
  margin-bottom: 20px;
}

.filter-bar {
  flex-wrap: wrap; /* 允许在小屏幕下换行 */
  gap: 12px; /* 统一子元素间距基准 */
}

/* 时间范围按钮组样式 */
.time-range-buttons {
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
}

/* 调整按钮内部 padding，避免按钮过宽 */
.time-range-buttons .el-button {
  padding: 6px 12px;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .el-date-picker {
    width: 280px !important; /* 小屏幕进一步缩短 */
  }
}
</style>